﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MovieAgentGadget.ActionScript.Library;
using MovieAgentGadget.Data;
using MovieAgentGadget.Promotion;
using MovieAgentGadget.Shared;
using ScriptCoreLib;
using ScriptCoreLib.ActionScript;
using ScriptCoreLib.ActionScript.DOM;
using ScriptCoreLib.ActionScript.DOM.Extensions;
using ScriptCoreLib.ActionScript.DOM.HTML;
using ScriptCoreLib.ActionScript.Extensions;
using ScriptCoreLib.ActionScript.flash.display;
using ScriptCoreLib.ActionScript.flash.external;
using ScriptCoreLib.ActionScript.flash.system;
using ScriptCoreLib.ActionScript.flash.text;
using ScriptCoreLib.ActionScript.flash.ui;
using ScriptCoreLib.ActionScript.flash.utils;
using ScriptCoreLib.Shared.Lambda;
using MovieAgent.Shared;

namespace MovieAgentGadget.ActionScript
{

	[GoogleGadget(
	   author_email = Info.EMail,
	   author_link = Info.Blog,
	   author = Info.Author,
	   category = Info.GoogleGadget.Category1,
	   category2 = Info.GoogleGadget.Category2,
	   screenshot = "",
	   thumbnail = "",
	   description = Info.Description,
	   width = DefaultWidth,
	   height = DefaultHeight,
	   title = Info.Title,
	   title_url = "http://zproxy.planet.ee/zmovies"

	)]
	[Script, ScriptApplicationEntryPoint(Width = 0, Height = 0, Feed = DefaultFeed)]
	[SWF(width = DefaultWidth, height = DefaultHeight)]
	public class MovieAgentGadgetOld : Sprite
	{
		// public const string DefaultFeed = "http://zproxy.planet.ee/zmovies/feed.xml?5";
		public const string DefaultFeed = "http://feeds2.feedburner.com/zmovies";

		public const int DefaultWidth = 800;
		public const int DefaultHeight = 400;

		// // change: C:\util\xampplite\apache\conf\httpd.conf

		// http://localhost/jsc/MovieAgentGadget/MovieAgentGadget.htm

		//Alias /jsc/MovieAgentGadget "C:\work\code.google\zmovies\MovieAgent\MovieAgentGadget\bin\Release\web"
		//<Directory "C:\work\code.google\zmovies\MovieAgent\MovieAgentGadget\bin\Release\web">
		//       Options Indexes FollowSymLinks ExecCGI
		//       AllowOverride All
		//       Order allow,deny
		//       Allow from all
		//</Directory>

		// http://curtismorley.com/2008/11/01/actionscript-security-error-2060-security-sandbox-violation/
		// http://mihai.bazon.net/blog/flash-s-externalinterface-and-ie
		// http://bugs.adobe.com/jira/browse/FP-692
		// http://team.mixmedia.com/index.php?title=ie_flash9_0_16_0_externalinterface_unkno&more=1&c=1&tb=1&pb=1



		/// <summary>
		/// Default constructor
		/// </summary>
		public MovieAgentGadgetOld()
		{
			Security.allowDomain("*");

			this.InvokeWhenStageIsReady(
				delegate
				{
					this.stage.scaleMode = StageScaleMode.NO_SCALE;
				}
			);

			var t = new TextField
			{
				multiline = true,
				text = "",
				background = true,

				x = 10,
				y = 10,
				width = 400,
				height = 300,
				alwaysShowSelection = true,
			}.AttachTo(this);




			var context = new ExternalContext();

			//context.Trace += e => t.appendText("\n" + e);
			context.ElementChanged +=
				delegate
				{

					context.Document.title = "ExternalContext...";
					context.Document.body.style.backgroundColor = "black";
					context.Document.body.style.color = "white";

					//1.ExternalAtDelay(
					//    @"document.getElementsByTagName('head')[0].innerHTML = '<link rel=""alternate"" href=""http://feeds2.feedburner.com/zmovies"" type=""application/rss+xml"" title="""" id="""">';"
					//);


					//"<link rel='alternate' href='http://feeds2.feedburner.com/zmovies' type='application/rss+xml' title='' id='' />".AttachAsDiv(context);
					@"<style>
					a img { border: 0; }
//					body { background-color: black; color: white; }
					</style>".AttachAsDiv(context);

					var Posters = new IHTMLDiv { }.AttachTo(context);

					Posters.style.textAlign = "center";


					var LaunchCooliris = default(Action<string>);


					#region PicLensContext

					var LaunchCoolirisButtom = new IHTMLButton { innerHTML = "<img src='http://lite.piclens.com/images/PicLensButton.png' />Cooliris" }.AttachTo(context);

					LaunchCoolirisButtom.onclick +=
						delegate
						{
							if (LaunchCooliris != null)
								LaunchCooliris(
									// "http://feeds2.feedburner.com/zmovies"
									DefaultFeed
								);

							LaunchCoolirisButtom.innerHTML = "launching...";

							1000.AtDelay(
								delegate
								{
									LaunchCoolirisButtom.innerHTML = "<img src='http://lite.piclens.com/images/PicLensButton.png' />Cooliris";
								}
							);
						};



					context.ToPlugin("PicLensContext", "PicLens.Context", "application/x-cooliris",
						CoolirisToken =>
						{
							if (CoolirisToken == null)
							{
								new IHTMLDiv { innerHTML = "Cooliris not found..." }.AttachTo(context);
								return;
							}

							new IHTMLDiv { innerHTML = "Cooliris found: " + context.GetGlobalPropertyString(CoolirisToken, "version") }.AttachTo(context);

							// we can launch, but should we?
							LaunchCooliris =
								feed =>
								{
									context.ExternalContext_token_call_string_string_string(
										CoolirisToken, "launch", feed, "", ""
									);
								};

						}
					);
					#endregion

					#region gears
					GoogleGears.Factory(context,
						f =>
						{

							if (f == null)
							{
								new IHTMLDiv { innerHTML = "gears not found..." }.AttachTo(context);
								return;
							}

							if (!f.GetPermission("zmovies", "http://code.google.com/images/codelabs_sm.png", "We will store your data near you!"))
							{
								new IHTMLDiv { innerHTML = "gears denied..." }.AttachTo(context);
								return;
							}

							new IHTMLDiv { innerHTML = "gears: " + f.GetBuildInfo() }.AttachTo(context);

							var db = f.Database;

							db.Open("demo5");

							db.BeforeExecute +=
								sql =>
								{
									t.appendText("\n" + sql);
								};

							db.Create(typeof(MyData1));

							db.Insert(
								new MyData1
								{
									Text = "Monkey!",
									Value = 100.Random()
								}
							);

							//context.Element.width = DefaultWidth / 2;
							//context.Element.height = DefaultHeight / 2;

							db.Fetch<MyData1>(typeof(MyData1)).ForEach(
								k =>
								{
									var s = new { k.Text, k.Value }.ToString();

									//t.appendText("\n" + s);

									new IHTMLDiv { innerHTML = "<b>" + s + "</b>" }.AttachTo(context);
								}
							);

							t.appendText("\n" + "done");
						}
					);
					#endregion

					Func<string, string> ShowImageForPixlr =
						target =>
							"<a href='http://www.pixlr.com/editor/?image=" + target + "' title='Edit in pixlr'><img src='" + target + "'  /></a>";

					Action<string> AddFromTinEye =
						e => e.ToTinEyeImageLink().ToImageForPixlr().AttachAsSpan(context);

					//"".ToImage().AttachAsSpan(context);
					//"".ToImage().AttachAsSpan(context);

					// good for 1 hour
					//AddFromTinEye.InvokeAsParams(
					//    "e72c46ecd5c6b77a8d13b02ec160d5d5999c44f8",
					//    "fb543268f4778bd4d24e0945f7ef177230f6da3a",
					//    "cf532d47905578bda99cc2379fcd5fa7b5b04731",
					//    "a6eafbc8ec96b0d390f0b7a4667093321cc138f3",
					//    "eec6ad41ba1fbe83125b0cfe0c29b6c2f10d9a50",
					//    "013849ea3f5c2c79235903a0afe51eedd373366f",
					//    "a6eafbc8ec96b0d390f0b7a4667093321cc138f3"
					//);
					//"e72c46ecd5c6b77a8d13b02ec160d5d5999c44f8".ToTinEyeImageLink().ToImageForPixlr().AttachAsSpan(context);
					//"fb543268f4778bd4d24e0945f7ef177230f6da3a".ToTinEyeImageLink().ToImageForPixlr().AttachAsSpan(context);


					// http://code.google.com/apis/youtube/player_parameters.html
					@"
<object 
	type='application/x-shockwave-flash' 
	data='http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=tv' 
	width='800' 
	height='400' 
	
	wmode='transparent' 
	id='tv'
	name='tv'

	allowFullScreen='true' 
	allowNetworking='all' 
	allowScriptAccess='always'>
  <param name='movie' value='http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=tv' />
</object>

					".AttachAsDiv(context);

					var player = new YouTubePlayer
					{
						id = "tv",
						
					};

					player.Token.Context = context;

					var CurrentMovie = "";
					var KnownMovies = new List<string>();


					// wait for it
					5000.AtDelay(
						delegate
						{
							context.Document.title = "ready?";

							player.onStateChange +=
								status =>
								{
									if (status == YouTubePlayer.States.ended)
									{
										if (CurrentMovie == "")
											CurrentMovie = KnownMovies.Random();
										else
											CurrentMovie = KnownMovies.Next(k => k == CurrentMovie);

										context.Document.title = "next: " + CurrentMovie;

										player.loadVideoById(CurrentMovie);
									}
									("status: " + (int)status).AttachAsDiv(context);
								};

							player.loadVideoById("ipeN8dtKxmc");
						}
					);


					Action<string, string> AddVideoButton =
						(video, text) =>
						{
							var v = new IHTMLButton { innerHTML = text }.AttachTo(context);

							v.onclick +=
								delegate
								{
									player.loadVideoById(video);
								};

						};

					Func<int, string> VideoText = i => "Video " + i;


					AddVideoButton.InvokeAsParams(VideoText,
						"6Y5Ad3Mg068",
						"Tf-K50n7mLM",
						"q02i_sF3Ilg",
						"Rr7jnYQf_2g"
					);



					var MuteButton = new IHTMLButton { innerHTML = "Mute" }.AttachTo(context);

					MuteButton.onclick +=
						delegate
						{
							player.mute();
						};

					var UnmuteButton = new IHTMLButton { innerHTML = "Unmute" }.AttachTo(context);

					UnmuteButton.onclick +=
						delegate
						{
							player.unMute();
						};

					@"
		<a href='http://feeds2.feedburner.com/%7Er/zmovies/%7E6/1'>
			<img src='http://feeds2.feedburner.com/zmovies.1.gif' alt='zmovies' style='border: 0pt none ;'>
		</a>
					".AttachAsDiv(context);

					var div1 = (IHTMLDiv)context.Document.createElement("div");
					div1.innerHTML = ShowImageForPixlr("http://gears.google.com/images/logo_153x43.gif");
					div1.AttachTo(context.Document.body);
					//context.Document.body.appendChild(div1);

					var div2 = new IHTMLDiv
					{
						innerHTML = ""
					};
					div2.AttachTo(context.Document.body);


					// javascript: alert(document.getElementById('tv').loadVideoById)
					// javascript: alert(document.getElementById('tv').CallFunction)

					//                    div2.innerHTML = @"
					//<span style='color: blue; border-bottom: 1px dotted blue;'>zmovies</span>
					//<hr />
					//<object 
					//	type='application/x-shockwave-flash' 
					//	data='http://apps.cooliris.com/embed/cooliris.swf' 
					//	width='380' 
					//	height='225' 
					//	
					//	flashvars='feed=http://feeds2.feedburner.com/zmovies' 
					//	id='tv'
					//	name='tv'
					//	allowFullScreen='true' 
					//	allowNetworking='all' 
					//	allowScriptAccess='always'>
					//  <param name='movie' value='http://apps.cooliris.com/embed/cooliris.swf' />
					//</object>
					//<hr />
					//					";


					var div3 = new IHTMLDiv
					{
						innerHTML = "hello world3"
					};
					div3.AttachTo(context.Document.body);

					var DefaultLink = new { Link = "", Title = "", Text = "" };
					var DefaultImage = new { Source = "", Alt = "", Title = "" };

					var ParseLink = DefaultLink.ToAnonymousConstructor(
						(string element) =>
						{
							var Link = "";
							var Title = "";
							var Text = "";

							element.
								ParseAttribute("href", value => Link = value).
								ParseAttribute("title", value => Title = value).
								ParseContent(value => Text = value).
								Parse();

							return new { Link, Title, Text };
						}
					);

					var ParseImage = DefaultImage.ToAnonymousConstructor(
						(string element) =>
						{
							var Source = "";
							var Alt = "";
							var Title = "";

							element.
								ParseAttribute("src", value => Source = value).
								ParseAttribute("alt", value => Alt = value).
								ParseAttribute("title", value => Title = value).
								ParseContent(null).
								Parse();

							return new { Source, Alt, Title };
						}
					);


					var addfeeditem = context.ToInbound<string>(
						feeditem =>
						{
							var FuturePoster = new Future<IHTMLImage>();

							feeditem.ParseElements(
								(tag, index, element) =>
								{
									("parse: " + tag).AttachAsDiv(context);

									if (tag == "a")
									{
										var a = ParseLink(element);

										((a.Text).Replace("<", "&lt;").Replace(">", "&gt;")).AttachAsDiv(context);

										//a.Text.AttachAsDiv(context);

										// google feed seems to revert bad html
										a.Text.Replace(">", "/>").ParseElements(
											(tag_, index_, element_) =>
											{
												("parse2: " + tag_).AttachAsDiv(context);

												if (tag_ == "img")
												{
													var img = ParseImage(element_);


													{
														var prefix = "http://www.youtube.com/v/";
														if (a.Link.StartsWith(prefix))
														{
															var key = a.Link.Substring(prefix.Length, a.Link.IndexOf("&") - prefix.Length);

															("youtube: " + key).AttachAsDiv(context);


															KnownMovies.Add(key);

															var div = new IHTMLDiv
															{
																innerHTML = img.Source.ToImage()
															}.AttachTo(context.Document.body);

															FuturePoster.Continue(
																(IHTMLImage Poster) =>
																{
																	("FuturePoster.Continue: " + key).AttachAsDiv(context);

																	Poster.style.cursor = "pointer";
																	Poster.onclick +=
																		delegate
																		{
																			("Poster.onclick: " + key).AttachAsDiv(context);
																			player.loadVideoById(key);
																		};
																}
															);
														}
													}
													{
														var prefix = "http://www.imdb.com/title/";
														if (a.Link.StartsWith(prefix))
														{
															//http://www.imdb.com/title/

															//img.ToString().AttachAsDiv(context);

															("title: " + a.Title).AttachAsDiv(context);


															FuturePoster.Value = new IHTMLImage
															{
																title = a.Title,
																src = img.Source
															}.AttachTo(Posters);
														}
													}
												}

											}
										);
									}
								}
							);

							//var youtubeimage_tag = "<a";
							//var youtubeimage_i = feeditem.IndexOf(youtubeimage_tag, offset);

							//var youtubeimage_end_tag = "</a>";
							//var youtubeimage_end_i = feeditem.IndexOf(youtubeimage_end_tag, youtubeimage_i);

							//var youtubeimage_data = feeditem.Substring(youtubeimage_i, youtubeimage_end_i - youtubeimage_i + youtubeimage_end_tag.Length);


							//var youtube_link = ParseLink(youtubeimage_data);
							//var youtube_image = ParseImage(youtube_link.Text);

							var z = (feeditem).Replace("<", "&lt;").Replace(">", "&gt;");


							new IHTMLDiv
							{
								innerHTML = "<textarea style='width:100%; height:25%'>" + z + "</textarea>"
							}.AttachTo(context.Document.body);
						}
					);

					// http://www.google.com/uds/Gfeeds?callback=hh&scoring=h&context=0&num=250&hl=en&output=json&q=http://zproxy.planet.ee/zmovies/feed.xml&v=1.0&nocache=0

					(@"
    <script>
function piper(dummy, result)
{
    for (var i=0; i<result.feed.entries.length; i++) {
       if (result.feed.entries[i].content) {
			document.getElementById('" + context.Element.id + "')['" + addfeeditem.Token + @"'](result.feed.entries[i].content);
       }
    }
}

    </script>

	<script src='http://www.google.com/uds/Gfeeds?callback=piper&scoring=h&context=0&num=250&hl=en&output=json&q=http://feeds2.feedburner.com/zmovies&v=1.0&nocache=0'></script>

<object 
	type='application/x-shockwave-flash' 
	height='295' 
	width='353' 
	id='jtv_player_flash' 
	data='http://www.justin.tv/widgets/jtv_player.swf?channel=szutka65' 
	bgcolor='#000000'>
	<param name='allowFullScreen' value='true' />
	<param name='movie' value='http://www.justin.tv/widgets/jtv_player.swf' />
	<param name='flashvars' value='channel=szutka65&auto_play=false&start_volume=25' />
</object>


<object 
	type='application/x-shockwave-flash' 
	height='295' 
	width='353' 
	id='jtv_player_flash' 
	data='http://www.justin.tv/widgets/jtv_player.swf?channel=stedawg21' 
	bgcolor='#000000'>
	<param name='allowFullScreen' value='true' />
	<param name='movie' value='http://www.justin.tv/widgets/jtv_player.swf' />
	<param name='flashvars' value='channel=stedawg21&auto_play=false&start_volume=25' />
</object>


<object 
	type='application/x-shockwave-flash' 
	height='295' 
	width='353' 
	id='jtv_player_flash' 
	data='http://www.ustream.tv/flash/live/1/514442' 
	bgcolor='#000000'>
	<param name='allowFullScreen' value='true' />
	<param name='movie' value='http://www.ustream.tv/flash/live/1/514442' />
	<param name='flashvars' value='auto_play=false&start_volume=25' />
</object>
").AttachAsDiv(context);

					#region timer
					var c = 0;
					100.AtInterval(
						delegate
						{
							c++;
							div3.innerHTML = "#" + c;
						}
					);
					#endregion


					//t.text = self.id;

					//self.width = 100;
					//self.height = 100;



				};

			context.ExternalAuthentication();

		}

	

	}



}